<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- layout布局 -->
      <el-row :gutter="20">
        <el-col :span="10">
          <!-- 搜索框 -->
          <el-input
            placeholder="请输入要查找的用户名或账号 "
            v-model="queryInfo.query"
            clearable
            @clear="getUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>

      <!-- 表单 -->
      <el-table
        ref="multipleTable"
        :data="userList"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        border
        stripe
      >
        <el-table-column type="index" width="55" label="#"> </el-table-column>
        <el-table-column prop="userList" label="头像">
          <template slot-scope="scope">
            <el-image
              style="width: 100px; height: 100px"
              :src="scope.row.url"
            ></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="userId" label="用户id"> </el-table-column>
        <el-table-column prop="username" label="账号"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <!-- 这里指定了一个宽度，才能撑下三个按钮 -->
        <el-table-column
          prop="address"
          label="操作"
          show-overflow-tooltip
          width="180px"
        >
          <!-- 这里也是使用了 插槽 -->
          <template slot-scope="scope">
            <!-- 编辑按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteById(scope.row)"
            ></el-button>
            <!-- 打开留言板 -->
            <el-button
              type="info"
              icon="el-icon-message"
              circle
              @click="showMessage(scope.row)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 3, 5]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 展示消息的对话框 -->
    <el-dialog
      title="消息列表"
      :visible.sync="msgDialogVisible"
      @close="msgDialogClosed"
    >
      <div class="dialogDiv">
        <!-- 头部 -->

        <!-- <el-card> -->
        <div class="info">
          <div
            v-if="concatList.length == 0"
            style="
               {
                height: 100px;
              }
            "
          >
            <el-empty description="消息为空"></el-empty>
          </div>
          <div
            v-else
            class="info-item"
            v-for="(item, i) in concatList"
            :key="i"
          >
            <!-- 是用户 -->
            <div class="isUser" v-if="item.userid != undefined">
              <div class="left">
                <div class="left-top">
                  <img :src="row.url" alt="" />
                </div>
                <div class="left-bottom">用户:{{ row.username }}</div>
              </div>
              <div class="right">
                <div class="right-top" v-if="item.pic != ''">
                  <img :src="item.pic" alt="" />
                </div>
                <div class="right-bottom" v-if="item.context != null">
                  {{ item.context }}
                </div>
                <!-- <div class="date">{{item.date}}</div> -->
              </div>
            </div>
            <!-- 是管理员 -->
            <div class="isAdmin" v-if="item.adminid != undefined">
              <div class="right">
                <div class="right-top" v-if="item.pic != ''">
                  <img :src="item.pic" alt="" />
                </div>
                <div class="right-bottom" v-if="item.context != null">
                  {{ item.context }}
                </div>
              </div>
              <div class="left">
                <div class="left-top">
                  <img :src="firstAdmin.url" alt="" />
                </div>
                <div class="left-bottom">管理员:{{ firstAdmin.adminname }}</div>
              </div>
              
              <!-- <div class="date">{{item.date}}</div> -->
            </div>
          </div>
        </div>
        <!-- </el-card> -->

        <el-card>
          <el-form :model="messageData" ref="msgFormRef" label-width="100px">
            <el-form-item label="发送的消息">
              <!-- 输入框 -->
              <el-input
                type="textarea"
                :autosize="{ minRows: 2, maxRows: 4 }"
                placeholder="请输入内容"
                v-model="messageData.textarea"
              >
              </el-input>
            </el-form-item>
            <el-form-item label="发送的图片">
              <!-- 上传图片 -->
              <el-upload
                class="message-uploader"
                action="http://localhost/touser/uploadPic"
                name="messageImg"
                :show-file-list="false"
                :on-success="handleMessageSuccess"
                :before-upload="beforeMessageUpload"
              >
                <img v-if="imageUrl3" :src="imageUrl3" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-form>
          <div class="msg-footer">
            <el-button @click="msgDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="msgSuccess">发送</el-button>
          </div>
        </el-card>
      </div>
    </el-dialog>

    <!-- 添加信息的对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible"
      @close="addDialogClosed"
    >
      <el-form
        :model="addForm"
        :rules="addFormrules"
        ref="addFormRef"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="头像">
          <!-- 上传头像 -->
          <el-upload
            class="avatar-uploader"
            action="http://localhost/user/uploadPic"
            :show-file-list="false"
            name="userImg"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addSuccess">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 修改信息的对话框 -->
    <el-dialog
      title="修改用户信息"
      :visible.sync="editDialogVisible"
      @close="editDialogClosed"
    >
      <el-form
        label-width="100px"
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
      >
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="editForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="头像">
          <!-- 上传头像 -->
          <el-upload
            class="avatar-uploader"
            action="http://localhost/user/uploadPic"
            :show-file-list="false"
            name="userImg"
            :on-success="handleAvatarSuccess2"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl2" :src="imageUrl2" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editSuccess">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>



<script>
export default {
  created() {
    this.getUserList();
    this.getFirstAdmin();
  },
  methods: {
    async getUserList() {
      const { data: res } = await this.$http.get(
        `/user/${this.queryInfo.pagenum}/${this.queryInfo.pagesize}?username=` +
          this.queryInfo.query
      );
      console.log(res, "分页获取到的用户数据");
      this.userList = res.data.records;
      this.total = res.data.total;
    },
    /* 清空添加表单的对话框 监听*/
    addDialogClosed() {
      this.$refs.addFormRef.resetFields();
    },
    editDialogClosed() {
      this.$refs.editFormRef.resetFields();
    },
    msgDialogClosed() {
      // this.$refs.msgFormRef.resetFields();
      this.imageUrl3 = "";
      this.messageData.url = "";
      this.messageData.textarea = "";
    },
    addSuccess() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (valid) {
          const { data: res } = await this.$http.post("/user/addUser", {
            username: this.addForm.username,
            password: this.addForm.password,
            email: this.addForm.email,
            url: this.url,
          });
          console.log(res, "我是添加成功之后的返回值");
          if (res.flag == true) {
            this.$message.success(res.msg);
            this.addDialogVisible = false;
            this.getUserList();
          } else {
            this.$message.error(res.msg);
          }
        }
      });
    },
    async showEditDialog(row) {
      console.log(row, "我是每一个的row");
      this.editDialogVisible = true;
      const { data: res } = await this.$http.get(
        `/user/getUserById/${row.row.userId}`
      );
      console.log(res, "按照id查找用户");
      this.editForm = res.data;
      this.imageUrl2 = res.data.url;
    },
    showMessage(row) {
      this.row = row;
      this.msgDialogVisible = true;
      this.getByUserid(row);
      this.getByAdminid(row);
      // this.sortDate()
    },
    editSuccess() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (valid) {
          const res = await this.$http.put("/user/update", {
            userId: this.editForm.userId,
            email: this.editForm.email,
            password: this.editForm.password,
            url: this.editForm.url,
          });
          console.log(res, "我是修改之后的返回");
          if (res.data.flag == true) {
            this.$message.success("修改成功");
            this.editDialogVisible = false;
            this.getUserList();
          } else {
            return this.$message.error("修改失败");
          }
        }
      });
    },
    deleteById(row) {
      console.log(row, "我是列数据用来删除的");
      this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await this.$http.delete("/user/delete/" + row.userId);
          this.getUserList();
          console.log(res, "我是删除之后的信息");
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //监听 pageesize 改变的事件
    handleSizeChange(newSize) {
      console.log(`每页 ${newSize} 条`);
      this.queryInfo.pagesize = newSize;
      this.getUserList();
    },
    // 监听 页码值 改变的事件
    handleCurrentChange(newPage) {
      console.log(`当前页: ${newPage}`);
      this.queryInfo.pagenum = newPage;
      this.getUserList();
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },

    // 上传图片所用
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      // console.log(this.imageUrl,"图片")
      this.url = res.data;
    },
    handleAvatarSuccess2(res, file) {
      this.imageUrl2 = URL.createObjectURL(file.raw);
      // console.log(this.imageUrl,"图片")
      this.editForm.url = res.data;
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    handleMessageSuccess(res, file) {
      this.imageUrl3 = URL.createObjectURL(file.raw);
      // console.log(this.imageUrl,"图片")
      this.messageData.url = res.data;
    },
    beforeMessageUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    async msgSuccess() {
      const { data: res } = await this.$http.post("/touser/add", {
        adminid: 1,
        touserid: this.row.userId,
        context: this.messageData.textarea,
        pic: this.messageData.url,
      });
      console.log(this.row);
      console.log(res, "向用户发送一条消息");
      this.getByUserid(this.row);
      this.getByAdminid(this.row);
      this.messageData.textarea = "";
      this.messageData.url = "";
      this.imageUrl3 = "";
    },
    //拿到用户给管理员的消息
    async getByUserid(row) {
      const { data: res } = await this.$http.get(
        `/toadmin/getByUserid/${row.userId}/1`
      );
      console.log(res, "用户给管理员的消息");
      this.getByUserList = res.data;
    },
    //拿到管理员给用户的消息
    async getByAdminid(row) {
      const { data: res } = await this.$http.get(
        `/touser/getByAdminid/1/${row.userId}`
      );
      console.log(res, "管理员给用户的");
      this.getByAdminList = res.data;
      this.sortDate();
    },
    sortDate() {
      this.concatList = this.getByUserList.concat(this.getByAdminList);
      this.concatList.sort((a, b) => {
        let date1 = new Date(a.date);
        let date2 = new Date(b.date);
        // return a.date.localeCompare(b.date);
        return date1 - date2;
      });
      console.log(this.concatList, "this.concatList");
    },
    //获取1号管理员的信息
    async getFirstAdmin() {
      const { data: res } = await this.$http.get(`/admin/selectById/1`);
      this.firstAdmin = res.data;
    },
  },
  data() {
    //验证邮箱的规则
    var checkEmail = (rule, value, callback) => {
      //验证邮箱的正则表达式
      var regEmail = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
      if (regEmail.test(value)) {
        return callback();
      }
      callback(new Error("请输入合法的邮箱"));
    };
    return {
      url: "",
      //用于添加
      imageUrl: "",
      //用于编辑
      imageUrl2: "",
      //用于查看消息
      imageUrl3: "",
      /* 添加用户表单 */
      addForm: {
        username: "",
        password: "",
        email: "",
        avatar_url: "",
        // mobile: '',
      },
      /*修改用户表单 */
      editForm: {
        userId: 0,
        username: "",
        password: "",
        email: "",
        avatar_url: "",
      },
      //获取用户列表的参数对象
      queryInfo: {
        query: "",
        //当前的页数
        pagenum: 1,
        //当前每页显示多少条数据
        pagesize: 3,
      },
      //展示消息的表
      messageData: {
        textarea: "",
        url: "",
      },
      getByUserList: [],
      getByAdminList: [],
      concatList: [],
      //用来保存当前用户的的信息
      row: {},
      //获取1号管理员的信息
      firstAdmin: [],
      userList: [],
      total: 0,
      multipleSelection: [],
      addDialogVisible: false,
      /* 编辑用户对话框是否显示 */
      editDialogVisible: false,
      // 消息列表的对话框是否展示
      msgDialogVisible: false,
      /* 添加表单的验证规则 */
      addFormrules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 5,
            max: 10,
            message: "长度在 5 到 10 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 5,
            max: 10,
            message: "长度在 5 到 10 个字符",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail },
        ],
      },
      /* 修改表单的验证规则 */
      editFormRules: {
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 5,
            max: 10,
            message: "长度在 5 到 10 个字符",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail },
        ],
      },
    };
  },
};
</script>

<style scoped>
.el-pagination {
  margin-top: 15px;
}
.el-card {
  margin: 15px 0;
}
.el-table {
  margin-top: 15px;
}

/* 添加头像的样式 */
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
/* .dialogDiv {
  height: 600px;
  overflow: auto;
} */
.msg-footer {
  float: right;
  padding-bottom: 15px;
}
/* .el-main {
  display: flex;
  height: 50vh;
  width: 100%;
  align-items: center;
} */
.info {
  background-color: rgb(234, 237, 244);
  padding: 5px 5px;
  height: 300px;
  overflow-y: auto; /*只是y方向*/
}
.info-item {
  /* float: left; */
}
.isUser,
.isAdmin {
  display: flex;
  /* position: relative; */
}
.isUser {
  /* position: absolute;
  left: 0; */
  /* float: left; */
  padding: 5px 0;
}
.isAdmin {
  /* position: absolute;
  right: 0; */
  /* float: right; */
  padding: 5px 0;
  margin-left: 600px;
}
.left-top img {
  width: 60px;
  height: 60px;
  border-radius: 50%;
}
.right-top img {
  width: 60px;
  height: 60px;
}
.left {
  padding-right: 12px;
}
.right {
  display: flex;
  flex-direction: column;
  justify-content: center;
  padding: 25px;
  background-color: rgb(149, 209, 247);
  border-radius: 75%;
}
/* .date{
  font-size: 6px;
} */
</style>